package cn.fjy.android.phone.worker;

import java.io.File;

import android.media.MediaRecorder;
import android.util.Log;
import cn.fjy.android.res.Constant;

/**
 *@author GrayF
 *2011-8-17
 *@version 1.0
 */
public class Recorder implements Runnable{
	private final static String tag = "Recorder";
	
	private MediaRecorder recorder = new MediaRecorder();
	
	private String recordFileName;
	
	private String FileType = ".3gp";
	
	public Recorder(String fileName){
		recordFileName = fileName;
		File file = new File(Constant.RECORD_FILEPATH);
		if(!file.exists()){
			try{
				file.mkdir();
			}catch (Exception e) {
				Log.i(tag, e.getMessage());
			}
		}
		init();
	}
	
	public void init(){
		Log.i(tag, "录音器初始化");
		recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		File recordFile = new File(Constant.RECORD_FILEPATH+File.separator+recordFileName+FileType);
		if(!recordFile.exists()){
			try{
				Log.i(tag, "创建录音文件");
				recordFile.createNewFile();
			}catch (Exception e) {
				Log.i(tag, e.getMessage());
			}
		}
		recorder.setOutputFile(recordFile.getAbsolutePath());
		try {
			recorder.prepare();
		} catch (Exception e) {
			Log.i(tag, e.getMessage());
		}
	}
	
	public void run(){
		start();
	}
	
	public void start(){
		try{
			Log.i(tag, "开始录音,"+recordFileName);
			recorder.start();
		}catch (Exception e) {
			Log.i(tag, e.getMessage());
		}
	}
	
	public void stop(){
		try{
			Log.i(tag, "结束录音,"+recordFileName);
			recorder.stop();
			recorder.reset();
			recorder.release();
		}catch (Exception e) {
			if(e!=null&&e.getMessage()!=null){
				Log.i(tag, e.getMessage());
			}
		}
	}
}

